<template>
  <div class="app-container">
    <!-- 权限检查 -->
    <div v-if="!hasPermission" class="no-permission">
      <el-alert
        title="权限不足"
        description="您没有权限访问此功能，请联系管理员"
        type="warning"
        :closable="false"
      />
      <br>
    </div>
    <el-tabs v-if="hasPermission" v-model="activeTab" @tab-click="handleTabClick">
      <!-- 单条消息发送 -->
      <el-tab-pane label="发送消息" name="single">
        <el-card class="box-card">
          <el-form
            ref="singleForm"
            :model="singleForm"
            :rules="singleRules"
            label-width="120px"
          >
            <el-form-item label="聊天ID" prop="chat_id">
              <el-input
                v-model="singleForm.chat_id"
                placeholder="请输入聊天ID (例如: 86138xxxxxxxx@c.us)"
                clearable
              />
            </el-form-item>

            <el-form-item label="WAHA会话" prop="wahasession_id">
              <el-select
                v-model="singleForm.wahasession_id"
                placeholder="选择WAHA会话（可选）"
                clearable
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="session in wahaSessions"
                  :key="session.id"
                  :label="`${session.session_name} (${session.phone})`"
                  :value="session.id"
                >
                  <span style="float: left">{{ session.session_name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ session.phone }}</span>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="消息类型" prop="message_type">
              <el-radio-group v-model="singleForm.message_type">
                <el-radio label="text">文本消息</el-radio>
                <el-radio label="image">图片消息</el-radio>
                <el-radio label="voice">语音消息</el-radio>
                <el-radio label="tts">文字转语音</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="消息内容" prop="content">
              <el-input
                v-if="singleForm.message_type === 'text'"
                v-model="singleForm.content"
                type="textarea"
                :rows="4"
                placeholder="请输入消息内容"
              />
              <div v-else-if="singleForm.message_type === 'image'" class="image-input-container">
                <!-- 粘贴区域 -->
                <div
                  class="paste-area"
                  tabindex="0"
                  @paste="handlePaste($event, 'single')"
                  @click="focusPasteArea($event)"
                  @dragover.prevent
                  @drop="handleDrop($event, 'single')"
                >
                  <div v-if="!singleForm.imagePreview" class="paste-tip">
                    <i class="el-icon-picture-outline" />
                    <div>点击此区域，然后粘贴图片 (Ctrl+V)</div>
                    <div class="sub-tip">或拖拽图片到此处</div>
                  </div>
                  <div v-else class="paste-images">
                    <div class="image-item">
                      <img :src="singleForm.imagePreview" class="preview-image">
                      <i class="el-icon-delete delete-icon" @click.stop="clearImage('single')" />
                    </div>
                  </div>
                </div>
                <!-- URL输入框 -->
                <el-input
                  v-model="singleForm.content"
                  type="textarea"
                  :rows="2"
                  placeholder="或手动输入图片URL或base64编码"
                  class="url-input"
                />
              </div>
              <div v-else-if="singleForm.message_type === 'voice'" class="voice-input-container">
                <!-- 录音区域 -->
                <div class="record-area">
                  <div class="record-controls">
                    <el-button
                      v-if="!singleForm.isRecording && !singleForm.audioPreview"
                      type="primary"
                      icon="el-icon-microphone"
                      :disabled="!isRecordingSupported"
                      @click="startRecording('single')"
                    >
                      开始录音
                    </el-button>

                    <div v-if="singleForm.isRecording" class="recording-indicator">
                      <el-button
                        type="danger"
                        icon="el-icon-video-pause"
                        @click="stopRecording('single')"
                      >
                        停止录音
                      </el-button>
                      <span class="recording-time">{{ formatRecordingTime(singleForm.recordingTime) }}</span>
                      <div class="recording-wave">
                        <div class="wave-dot" />
                        <div class="wave-dot" />
                        <div class="wave-dot" />
                      </div>
                    </div>

                    <div v-if="singleForm.audioPreview" class="audio-preview">
                      <audio :src="singleForm.audioPreview" controls />
                      <el-button
                        type="text"
                        icon="el-icon-delete"
                        class="clear-audio-btn"
                        @click="clearAudio('single')"
                      >
                        重新录音
                      </el-button>
                    </div>
                  </div>

                  <div v-if="!isRecordingSupported" class="recording-tip error">
                    <i class="el-icon-warning" />
                    您的浏览器不支持录音功能，请使用现代浏览器
                  </div>
                  <div v-else class="recording-tip">
                    <i class="el-icon-info" />
                    点击开始录音按钮进行录音，将使用WebM格式，录音完成后会自动转换为base64格式
                  </div>
                </div>

                <!-- URL输入框 -->
                <el-input
                  v-model="singleForm.content"
                  type="textarea"
                  :rows="2"
                  placeholder="或手动输入语音文件URL或base64编码"
                  class="url-input"
                />
              </div>
              <div v-else-if="singleForm.message_type === 'tts'" class="tts-input-container">
                <el-input
                  v-model="singleForm.content"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入要转换为语音的文字内容（最多1000字符）"
                  maxlength="1000"
                  show-word-limit
                />
              </div>
              <el-input
                v-else
                v-model="singleForm.content"
                placeholder="请输入文件URL或base64编码"
              />
            </el-form-item>

            <el-form-item
              v-if="singleForm.message_type === 'image'"
              label="图片说明"
              prop="caption"
            >
              <el-input
                v-model="singleForm.caption"
                placeholder="图片说明文字（可选）"
              />
            </el-form-item>

            <!-- TTS参数配置 -->
            <template v-if="singleForm.message_type === 'tts'">
              <el-form-item label="语音服务商" prop="provider">
                <el-radio-group v-model="singleForm.provider">
                  <el-radio label="openai">OpenAI</el-radio>
                  <el-radio label="amazon">Amazon Polly</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="语音类型" prop="voice_type">
                <el-select
                  v-model="singleForm.voice_type"
                  placeholder="选择语音类型"
                  style="width: 100%"
                >
                  <el-option
                    v-for="voice in getVoiceOptions(singleForm.provider)"
                    :key="voice.value"
                    :label="voice.label"
                    :value="voice.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="语言" prop="language">
                <el-select
                  v-model="singleForm.language"
                  placeholder="选择语言"
                  style="width: 100%"
                >
                  <el-option
                    v-for="lang in getLanguageOptions(singleForm.provider)"
                    :key="lang.value"
                    :label="lang.label"
                    :value="lang.value"
                  />
                </el-select>
              </el-form-item>
            </template>

            <el-form-item>
              <el-button
                type="primary"
                :loading="singleLoading"
                @click="sendSingleMessage"
              >
                发送消息
              </el-button>
              <el-button @click="resetSingleForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>

      <!-- 批量消息发送 -->
      <el-tab-pane label="批量发送" name="bulk">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>批量发送消息</span>
          </div>

          <el-form
            ref="bulkForm"
            :model="bulkForm"
            :rules="bulkRules"
            label-width="120px"
          >
            <el-form-item label="聊天ID列表" prop="chat_ids">
              <el-input
                v-model="bulkForm.chat_ids_text"
                type="textarea"
                :rows="6"
                placeholder="请输入聊天ID，每行一个&#10;例如：&#10;86138xxxxxxxx@c.us&#10;86139xxxxxxxx@c.us"
                @blur="parseChatIds"
              />
              <div class="form-tip">
                共 {{ bulkForm.chat_ids.length }} 个聊天ID
              </div>
            </el-form-item>

            <el-form-item label="WAHA会话" prop="wahasession_id">
              <el-select
                v-model="bulkForm.wahasession_id"
                placeholder="请选择WAHA会话"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="session in wahaSessions"
                  :key="session.id"
                  :label="`${session.session_name} (${session.phone})`"
                  :value="session.id"
                >
                  <span style="float: left">{{ session.session_name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ session.phone }}</span>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="消息类型" prop="message_type">
              <el-radio-group v-model="bulkForm.message_type">
                <el-radio label="text">文本消息</el-radio>
                <el-radio label="image">图片消息</el-radio>
                <el-radio label="voice">语音消息</el-radio>
                <el-radio label="tts">文字转语音</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="消息内容" prop="content">
              <el-input
                v-if="bulkForm.message_type === 'text'"
                v-model="bulkForm.content"
                type="textarea"
                :rows="4"
                placeholder="请输入消息内容"
              />
              <div v-else-if="bulkForm.message_type === 'image'" class="image-input-container">
                <!-- 粘贴区域 -->
                <div
                  class="paste-area"
                  tabindex="0"
                  @paste="handlePaste($event, 'bulk')"
                  @click="focusPasteArea($event)"
                  @dragover.prevent
                  @drop="handleDrop($event, 'bulk')"
                >
                  <div v-if="!bulkForm.imagePreview" class="paste-tip">
                    <i class="el-icon-picture-outline" />
                    <div>点击此区域，然后粘贴图片 (Ctrl+V)</div>
                    <div class="sub-tip">或拖拽图片到此处</div>
                  </div>
                  <div v-else class="paste-images">
                    <div class="image-item">
                      <img :src="bulkForm.imagePreview" class="preview-image">
                      <i class="el-icon-delete delete-icon" @click.stop="clearImage('bulk')" />
                    </div>
                  </div>
                </div>
                <!-- URL输入框 -->
                <el-input
                  v-model="bulkForm.content"
                  type="textarea"
                  :rows="2"
                  placeholder="或手动输入图片URL或base64编码"
                  class="url-input"
                />
              </div>
              <div v-else-if="bulkForm.message_type === 'voice'" class="voice-input-container">
                <!-- 录音区域 -->
                <div class="record-area">
                  <div class="record-controls">
                    <el-button
                      v-if="!bulkForm.isRecording && !bulkForm.audioPreview"
                      type="primary"
                      icon="el-icon-microphone"
                      :disabled="!isRecordingSupported"
                      @click="startRecording('bulk')"
                    >
                      开始录音
                    </el-button>

                    <div v-if="bulkForm.isRecording" class="recording-indicator">
                      <el-button
                        type="danger"
                        icon="el-icon-video-pause"
                        @click="stopRecording('bulk')"
                      >
                        停止录音
                      </el-button>
                      <span class="recording-time">{{ formatRecordingTime(bulkForm.recordingTime) }}</span>
                      <div class="recording-wave">
                        <div class="wave-dot" />
                        <div class="wave-dot" />
                        <div class="wave-dot" />
                      </div>
                    </div>

                    <div v-if="bulkForm.audioPreview" class="audio-preview">
                      <audio :src="bulkForm.audioPreview" controls />
                      <el-button
                        type="text"
                        icon="el-icon-delete"
                        class="clear-audio-btn"
                        @click="clearAudio('bulk')"
                      >
                        重新录音
                      </el-button>
                    </div>
                  </div>

                  <div v-if="!isRecordingSupported" class="recording-tip error">
                    <i class="el-icon-warning" />
                    您的浏览器不支持录音功能，请使用现代浏览器
                  </div>
                  <div v-else class="recording-tip">
                    <i class="el-icon-info" />
                    点击开始录音按钮进行录音，将使用WebM格式，录音完成后会自动转换为base64格式
                  </div>
                </div>

                <!-- URL输入框 -->
                <el-input
                  v-model="bulkForm.content"
                  type="textarea"
                  :rows="2"
                  placeholder="或手动输入语音文件URL或base64编码"
                  class="url-input"
                />
              </div>
              <div v-else-if="bulkForm.message_type === 'tts'" class="tts-input-container">
                <el-input
                  v-model="bulkForm.content"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入要转换为语音的文字内容（最多1000字符）"
                  maxlength="1000"
                  show-word-limit
                />
              </div>
              <el-input
                v-else
                v-model="bulkForm.content"
                placeholder="请输入文件URL或base64编码"
              />
            </el-form-item>

            <el-form-item
              v-if="bulkForm.message_type === 'image'"
              label="图片说明"
              prop="caption"
            >
              <el-input
                v-model="bulkForm.caption"
                placeholder="图片说明文字（可选）"
              />
            </el-form-item>

            <!-- TTS参数配置 -->
            <template v-if="bulkForm.message_type === 'tts'">
              <el-form-item label="语音服务商" prop="provider">
                <el-radio-group v-model="bulkForm.provider">
                  <el-radio label="openai">OpenAI</el-radio>
                  <el-radio label="amazon">Amazon Polly</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="语音类型" prop="voice_type">
                <el-select
                  v-model="bulkForm.voice_type"
                  placeholder="选择语音类型"
                  style="width: 100%"
                >
                  <el-option
                    v-for="voice in getVoiceOptions(bulkForm.provider)"
                    :key="voice.value"
                    :label="voice.label"
                    :value="voice.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="语言" prop="language">
                <el-select
                  v-model="bulkForm.language"
                  placeholder="选择语言"
                  style="width: 100%"
                >
                  <el-option
                    v-for="lang in getLanguageOptions(bulkForm.provider)"
                    :key="lang.value"
                    :label="lang.label"
                    :value="lang.value"
                  />
                </el-select>
              </el-form-item>
            </template>

            <el-form-item label="发送间隔" prop="delay">
              <el-input-number
                v-model="bulkForm.delay"
                :min="0"
                :step="0.5"
                placeholder="发送间隔（秒）"
              />
              <span class="form-tip">秒，0表示不延迟</span>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                :loading="bulkLoading"
                @click="sendBulkMessages"
              >
                批量发送
              </el-button>
              <el-button @click="resetBulkForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 发送结果 -->
    <el-card v-if="hasPermission && sendResults.length > 0" class="box-card" style="margin-top: 20px">
      <div slot="header" class="clearfix">
        <span>发送结果</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="clearResults">
          清空结果
        </el-button>
      </div>

      <el-table :data="sendResults" style="width: 100%">
        <el-table-column prop="time" label="时间" width="180">
          <template slot-scope="scope">
            {{ formatTime(scope.row.time) }}
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100" />
        <el-table-column prop="chat_id" label="聊天ID" width="200" />
        <el-table-column prop="message_type" label="消息类型" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.success ? 'success' : 'danger'">
              {{ scope.row.success ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="message" label="结果" />
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { sendWhatsAppMessage, sendBulkWhatsAppMessages, sendTextToVoice } from '@/api/chatbot/message'
import { getWahaSessionList } from '@/api/chatbot/waha-session'

export default {
  name: 'SendMessage',
  data() {
    return {
      activeTab: 'single',
      singleLoading: false,
      bulkLoading: false,
      wahaSessions: [],
      sendResults: [],

      // 录音相关
      mediaRecorder: null,
      recordedChunks: [],
      recordingTimer: null,

      // 单条消息表单
      singleForm: {
        chat_id: '',
        wahasession_id: '', // 将在loadWahaSessions中自动设置为第一个会话
        message_type: 'text',
        content: '',
        caption: '',
        imagePreview: '',
        isRecording: false,
        recordingTime: 0,
        audioPreview: '',
        // TTS相关字段
        provider: 'openai',
        voice_type: 'default',
        language: 'zh-CN'
      },

      // 批量消息表单
      bulkForm: {
        chat_ids_text: '',
        chat_ids: [],
        wahasession_id: '', // 将在loadWahaSessions中自动设置为第一个会话
        message_type: 'text',
        content: '',
        caption: '',
        delay: 1,
        imagePreview: '',
        isRecording: false,
        recordingTime: 0,
        audioPreview: '',
        // TTS相关字段
        provider: 'openai',
        voice_type: 'default',
        language: 'zh-CN'
      },

      // 表单验证规则
      singleRules: {
        chat_id: [
          { required: true, message: '请输入聊天ID', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入消息内容', trigger: 'blur' },
          { max: 1000, message: 'TTS文字内容不能超过1000个字符', trigger: 'blur' }
        ],
        wahasession_id: [
          {
            validator: (rule, value, callback) => {
              if (this.singleForm.message_type === 'tts' && !value) {
                callback(new Error('发送TTS消息时必须选择WAHA会话'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ]
      },

      bulkRules: {
        chat_ids_text: [
          { required: true, message: '请输入聊天ID列表', trigger: 'blur' }
        ],
        wahasession_id: [
          { required: true, message: '请选择WAHA会话', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入消息内容', trigger: 'blur' },
          { max: 1000, message: 'TTS文字内容不能超过1000个字符', trigger: 'blur' }
        ]
      }
    }
  },

  computed: {
    // 权限检查
    hasPermission() {
      return this.$store.getters.roles.indexOf('chatbot_user') !== -1 ||
             this.$store.getters.roles.indexOf('admin') !== -1
    },

    // 录音功能支持检查
    isRecordingSupported() {
      return navigator.mediaDevices && navigator.mediaDevices.getUserMedia
    }
  },

  created() {
    if (this.hasPermission) {
      this.loadWahaSessions()
    }
  },

  beforeDestroy() {
    // 清理录音相关资源
    if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
      this.mediaRecorder.stop()
      this.mediaRecorder.stream.getTracks().forEach(track => track.stop())
    }

    if (this.recordingTimer) {
      clearInterval(this.recordingTimer)
    }

    // 清理音频预览URL
    if (this.singleForm.audioPreview) {
      URL.revokeObjectURL(this.singleForm.audioPreview)
    }
    if (this.bulkForm.audioPreview) {
      URL.revokeObjectURL(this.bulkForm.audioPreview)
    }
  },

  methods: {
    // 加载WAHA会话列表
    async loadWahaSessions() {
      try {
        const response = await getWahaSessionList()
        if (response.success) {
          // 只显示状态为online的会话（对应working状态）
          this.wahaSessions = (response.data.data || []).filter(session =>
            session.session_status === 'online'
          )

          // 自动选择第一个会话作为默认值
          if (this.wahaSessions.length > 0) {
            const firstSessionId = this.wahaSessions[0].id
            this.singleForm.wahasession_id = firstSessionId
            this.bulkForm.wahasession_id = firstSessionId
          }
        } else {
          this.$message.error(response.msg || '加载WAHA会话列表失败')
        }
      } catch (error) {
        console.error('加载WAHA会话列表失败:', error)
        this.$message.error('加载WAHA会话列表失败')
      }
    },

    // 解析聊天ID列表
    parseChatIds() {
      const ids = this.bulkForm.chat_ids_text
        .split('\n')
        .map(id => id.trim())
        .filter(id => id.length > 0)
      this.bulkForm.chat_ids = ids
    },

    // 发送单条消息
    async sendSingleMessage() {
      this.$refs.singleForm.validate(async(valid) => {
        if (!valid) return

        this.singleLoading = true
        try {
          let response

          if (this.singleForm.message_type === 'tts') {
            // 处理TTS消息
            const params = {
              chat_id: this.singleForm.chat_id,
              text: this.singleForm.content,
              wahasession_id: this.singleForm.wahasession_id,
              provider: this.singleForm.provider,
              voice_type: this.singleForm.voice_type,
              language: this.singleForm.language
            }

            response = await sendTextToVoice(params)
          } else {
            // 处理普通消息
            const params = {
              chat_id: this.singleForm.chat_id,
              message_type: this.singleForm.message_type,
              content: this.singleForm.content
            }

            if (this.singleForm.wahasession_id) {
              params.wahasession_id = this.singleForm.wahasession_id
            }

            if (this.singleForm.message_type === 'image' && this.singleForm.caption) {
              params.caption = this.singleForm.caption
            }

            response = await sendWhatsAppMessage(params)
          }

          if (response.success) {
            this.$message.success('消息发送成功')
            this.addSendResult({
              type: '单条发送',
              chat_id: this.singleForm.chat_id,
              message_type: this.singleForm.message_type,
              success: true,
              message: '发送成功'
            })
          } else {
            this.$message.error(response.msg || '发送失败')
            this.addSendResult({
              type: '单条发送',
              chat_id: this.singleForm.chat_id,
              message_type: this.singleForm.message_type,
              success: false,
              message: response.msg || '发送失败'
            })
          }
        } catch (error) {
          console.error('发送消息失败:', error)
          this.$message.error('发送消息失败: ' + error.message)
          this.addSendResult({
            type: '单条发送',
            chat_id: this.singleForm.chat_id,
            message_type: this.singleForm.message_type,
            success: false,
            message: error.message
          })
        } finally {
          this.singleLoading = false
        }
      })
    },

    // 批量发送消息
    async sendBulkMessages() {
      this.parseChatIds()
      this.$refs.bulkForm.validate(async(valid) => {
        if (!valid) return

        if (this.bulkForm.chat_ids.length === 0) {
          this.$message.error('请输入有效的聊天ID列表')
          return
        }

        this.bulkLoading = true
        try {
          let response

          if (this.bulkForm.message_type === 'tts') {
            // TTS消息目前不支持批量发送，需要逐个发送
            this.$message.info('TTS消息将逐个发送，请稍候...')

            const results = []
            for (let i = 0; i < this.bulkForm.chat_ids.length; i++) {
              const chat_id = this.bulkForm.chat_ids[i]

              try {
                const params = {
                  chat_id: chat_id,
                  text: this.bulkForm.content,
                  wahasession_id: this.bulkForm.wahasession_id,
                  provider: this.bulkForm.provider,
                  voice_type: this.bulkForm.voice_type,
                  language: this.bulkForm.language
                }

                const singleResponse = await sendTextToVoice(params)
                results.push({
                  chat_id: chat_id,
                  success: singleResponse.success
                })

                this.addSendResult({
                  type: 'TTS批量发送',
                  chat_id: chat_id,
                  message_type: 'tts',
                  success: singleResponse.success,
                  message: singleResponse.success ? '发送成功' : '发送失败'
                })

                // 延迟处理
                if (this.bulkForm.delay > 0 && i < this.bulkForm.chat_ids.length - 1) {
                  await new Promise(resolve => setTimeout(resolve, this.bulkForm.delay * 1000))
                }
              } catch (error) {
                results.push({
                  chat_id: chat_id,
                  success: false
                })

                this.addSendResult({
                  type: 'TTS批量发送',
                  chat_id: chat_id,
                  message_type: 'tts',
                  success: false,
                  message: error.message
                })
              }
            }

            const successCount = results.filter(r => r.success).length
            this.$message.success(`TTS批量发送完成，成功: ${successCount}/${results.length}`)
            return
          } else {
            // 处理普通消息批量发送
            const params = {
              chat_ids: this.bulkForm.chat_ids,
              wahasession_id: this.bulkForm.wahasession_id,
              message_type: this.bulkForm.message_type,
              content: this.bulkForm.content,
              delay: this.bulkForm.delay
            }

            if (this.bulkForm.message_type === 'image' && this.bulkForm.caption) {
              params.caption = this.bulkForm.caption
            }

            response = await sendBulkWhatsAppMessages(params)
          }

          if (response.success) {
            const data = response.data
            this.$message.success(response.msg)

            // 添加批量发送结果
            if (data.results) {
              data.results.forEach(result => {
                this.addSendResult({
                  type: '批量发送',
                  chat_id: result.chat_id,
                  message_type: this.bulkForm.message_type,
                  success: result.success,
                  message: result.success ? '发送成功' : '发送失败'
                })
              })
            }
          } else {
            this.$message.error(response.msg || '批量发送失败')
          }
        } catch (error) {
          console.error('批量发送失败:', error)
          this.$message.error('批量发送失败: ' + error.message)
        } finally {
          this.bulkLoading = false
        }
      })
    },

    // 添加发送结果
    addSendResult(result) {
      this.sendResults.unshift({
        ...result,
        time: new Date()
      })

      // 只保留最近100条记录
      if (this.sendResults.length > 100) {
        this.sendResults = this.sendResults.slice(0, 100)
      }
    },

    // 格式化时间
    formatTime(time) {
      return time.toLocaleString()
    },

    // 清空结果
    clearResults() {
      this.sendResults = []
    },

    // 重置单条消息表单
    resetSingleForm() {
      this.$refs.singleForm.resetFields()
      const defaultSessionId = this.wahaSessions.length > 0 ? this.wahaSessions[0].id : ''
      this.singleForm = {
        chat_id: '',
        wahasession_id: defaultSessionId,
        message_type: 'text',
        content: '',
        caption: '',
        imagePreview: '',
        isRecording: false,
        recordingTime: 0,
        audioPreview: '',
        // TTS相关字段
        provider: 'openai',
        voice_type: 'default',
        language: 'zh-CN'
      }
    },

    // 重置批量消息表单
    resetBulkForm() {
      this.$refs.bulkForm.resetFields()
      const defaultSessionId = this.wahaSessions.length > 0 ? this.wahaSessions[0].id : ''
      this.bulkForm = {
        chat_ids_text: '',
        chat_ids: [],
        wahasession_id: defaultSessionId,
        message_type: 'text',
        content: '',
        caption: '',
        delay: 1,
        imagePreview: '',
        isRecording: false,
        recordingTime: 0,
        audioPreview: '',
        // TTS相关字段
        provider: 'openai',
        voice_type: 'default',
        language: 'zh-CN'
      }
    },

    // 标签页切换
    handleTabClick(tab) {
      // 可以在这里处理标签页切换逻辑
    },

    // 处理粘贴图片
    handlePaste(event, formType) {
      const items = (event.clipboardData || event.originalEvent.clipboardData).items
      for (const item of items) {
        if (item.type.indexOf('image') === 0) {
          event.preventDefault()
          const file = item.getAsFile()
          this.readFileAsBase64(file, formType)
          break
        }
      }
    },

    // 将文件读取为base64
    readFileAsBase64(file, formType) {
      const reader = new FileReader()
      reader.onload = (e) => {
        const base64 = e.target.result
        if (formType === 'single') {
          this.singleForm.content = base64
          this.singleForm.imagePreview = base64
        } else if (formType === 'bulk') {
          this.bulkForm.content = base64
          this.bulkForm.imagePreview = base64
        }
        this.$message.success('图片已粘贴成功')
      }
      reader.onerror = () => {
        this.$message.error('图片读取失败')
      }
      reader.readAsDataURL(file)
    },

    // 清除图片
    clearImage(formType) {
      if (formType === 'single') {
        this.singleForm.content = ''
        this.singleForm.imagePreview = ''
      } else if (formType === 'bulk') {
        this.bulkForm.content = ''
        this.bulkForm.imagePreview = ''
      }
    },

    // 粘贴区域获得焦点
    focusPasteArea(event) {
      event.target.focus()
    },

    // 处理拖拽上传
    handleDrop(event, formType) {
      event.preventDefault()
      const files = event.dataTransfer.files
      if (files.length > 0) {
        const file = files[0]
        if (file.type.indexOf('image') === 0) {
          this.readFileAsBase64(file, formType)
        } else {
          this.$message.error('请上传图片文件')
        }
      }
    },

    // 开始录音
    async startRecording(formType) {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true })

        this.recordedChunks = []

        // 优先使用WebM格式
        let mimeType = 'audio/webm;codecs=opus'
        if (!MediaRecorder.isTypeSupported(mimeType)) {
          // 备选方案1：通用WebM格式
          mimeType = 'audio/webm'
          if (!MediaRecorder.isTypeSupported(mimeType)) {
            // 备选方案2：OGG容器的OPUS编码
            mimeType = 'audio/ogg;codecs=opus'
            if (!MediaRecorder.isTypeSupported(mimeType)) {
              // 最后备选：使用默认格式
              mimeType = ''
              this.$message.warning('您的浏览器不支持WebM录制，将使用浏览器默认格式')
            }
          }
        }

        this.mediaRecorder = new MediaRecorder(stream, mimeType ? { mimeType } : {})

        this.mediaRecorder.addEventListener('dataavailable', (event) => {
          if (event.data.size > 0) {
            this.recordedChunks.push(event.data)
          }
        })

        this.mediaRecorder.addEventListener('stop', () => {
          this.handleRecordingStop(formType)
        })

        this[`${formType}Form`].isRecording = true
        this[`${formType}Form`].recordingTime = 0

        // 启动录音时间计数器
        this.recordingTimer = setInterval(() => {
          this[`${formType}Form`].recordingTime += 1
        }, 1000)

        this.mediaRecorder.start()
        this.$message.success('录音已开始')
      } catch (error) {
        console.error('录音启动失败:', error)
        this.$message.error('录音启动失败，请检查麦克风权限')
      }
    },

    // 停止录音
    stopRecording(formType) {
      if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
        this.mediaRecorder.stop()
        this.mediaRecorder.stream.getTracks().forEach(track => track.stop())

        this[`${formType}Form`].isRecording = false

        if (this.recordingTimer) {
          clearInterval(this.recordingTimer)
          this.recordingTimer = null
        }
      }
    },

    // 处理录音停止
    handleRecordingStop(formType) {
      // 确定最终的MIME类型
      let mimeType = 'audio/webm;codecs=opus'
      if (!MediaRecorder.isTypeSupported(mimeType)) {
        mimeType = 'audio/webm'
        if (!MediaRecorder.isTypeSupported(mimeType)) {
          mimeType = 'audio/ogg;codecs=opus'
          if (!MediaRecorder.isTypeSupported(mimeType)) {
            mimeType = 'audio/webm'
          }
        }
      }

      const blob = new Blob(this.recordedChunks, { type: mimeType })
      const audioUrl = URL.createObjectURL(blob)

      // 设置音频预览
      this[`${formType}Form`].audioPreview = audioUrl

      // 转换为base64
      const reader = new FileReader()
      reader.onload = () => {
        const base64 = reader.result
        this[`${formType}Form`].content = base64

        const formatInfo = mimeType.includes('opus') ? 'WebM/OPUS格式'
          : mimeType.includes('webm') ? 'WebM格式'
            : mimeType.includes('ogg') ? 'OGG/OPUS格式' : '默认格式'
        this.$message.success(`录音完成，已转换为base64格式 (${formatInfo})`)
      }
      reader.onerror = () => {
        this.$message.error('录音文件转换失败')
      }
      reader.readAsDataURL(blob)
    },

    // 清除音频
    clearAudio(formType) {
      this[`${formType}Form`].content = ''
      this[`${formType}Form`].audioPreview = ''
    },

    // 格式化录音时间
    formatRecordingTime(seconds) {
      const minutes = Math.floor(seconds / 60)
      const remainingSeconds = seconds % 60
      return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
    },

    // 获取语音类型选项
    getVoiceOptions(provider) {
      if (provider === 'openai') {
        return [
          { label: '默认语音', value: 'default' },
          { label: '女性声音 - Alloy', value: 'alloy' },
          { label: '男性声音 - Echo', value: 'echo' },
          { label: '女性声音 - Fable', value: 'fable' },
          { label: '男性声音 - Onyx', value: 'onyx' },
          { label: '女性声音 - Nova', value: 'nova' },
          { label: '男性声音 - Shimmer', value: 'shimmer' }
        ]
      } else if (provider === 'amazon') {
        return [
          { label: '默认语音', value: 'default' },
          { label: '中文女性 - Zhiyu', value: 'Zhiyu' },
          { label: '英语女性 - Joanna', value: 'Joanna' },
          { label: '英语男性 - Matthew', value: 'Matthew' },
          { label: '英语女性 - Amy', value: 'Amy' },
          { label: '英语男性 - Brian', value: 'Brian' }
        ]
      }
      return [{ label: '默认语音', value: 'default' }]
    },

    // 获取语言选项
    getLanguageOptions(provider) {
      if (provider === 'openai') {
        return [
          { label: '中文(简体)', value: 'zh-CN' },
          { label: '英语', value: 'en-US' },
          { label: '日语', value: 'ja-JP' },
          { label: '韩语', value: 'ko-KR' },
          { label: '法语', value: 'fr-FR' },
          { label: '德语', value: 'de-DE' },
          { label: '西班牙语', value: 'es-ES' }
        ]
      } else if (provider === 'amazon') {
        return [
          { label: '中文(简体)', value: 'zh-CN' },
          { label: '英语(美国)', value: 'en-US' },
          { label: '英语(英国)', value: 'en-GB' },
          { label: '日语', value: 'ja-JP' },
          { label: '韩语', value: 'ko-KR' },
          { label: '法语', value: 'fr-FR' },
          { label: '德语', value: 'de-DE' },
          { label: '西班牙语', value: 'es-ES' }
        ]
      }
      return [{ label: '中文(简体)', value: 'zh-CN' }]
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.image-input-container {
  margin-bottom: 10px;
}

.paste-area {
  border: 2px dashed #ddd;
  border-radius: 6px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s ease;
  margin-bottom: 10px;
  min-height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.paste-area:hover {
  border-color: #409eff;
}

.paste-area:focus {
  outline: none;
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.paste-tip {
  text-align: center;
  color: #909399;
}

.paste-tip i {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 10px;
  display: block;
}

.paste-tip div {
  margin: 5px 0;
}

.sub-tip {
  font-size: 12px;
  color: #c0c4cc;
}

.paste-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: center;
}

.image-item {
  position: relative;
  display: inline-block;
}

.preview-image {
  max-width: 150px;
  max-height: 120px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.delete-icon {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #f56c6c;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 12px;
}

.delete-icon:hover {
  background: #f78989;
}

.url-input {
  margin-top: 10px;
}

.voice-input-container {
  margin-bottom: 10px;
}

.record-area {
  margin-bottom: 10px;
}

.record-controls {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  gap: 15px;
}

.recording-indicator {
  display: flex;
  align-items: center;
  gap: 15px;
  background: #f5f7fa;
  padding: 15px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.recording-time {
  font-size: 16px;
  font-weight: bold;
  color: #e6a23c;
  min-width: 60px;
}

.recording-wave {
  display: flex;
  align-items: center;
  gap: 3px;
}

.wave-dot {
  width: 8px;
  height: 8px;
  background: #e6a23c;
  border-radius: 50%;
  animation: wave 1.4s ease-in-out infinite both;
}

.wave-dot:nth-child(1) {
  animation-delay: -0.32s;
}

.wave-dot:nth-child(2) {
  animation-delay: -0.16s;
}

.wave-dot:nth-child(3) {
  animation-delay: 0s;
}

@keyframes wave {
  0%, 40%, 100% {
    transform: scale(0.8);
    opacity: 0.6;
  }
  20% {
    transform: scale(1.2);
    opacity: 1;
  }
}

.audio-preview {
  margin-top: 10px;
  padding: 15px;
  background: #f0f9ff;
  border: 1px solid #409eff;
  border-radius: 8px;
  text-align: center;
}

.audio-preview audio {
  width: 100%;
  max-width: 400px;
}

.recording-tip {
  margin-top: 10px;
  padding: 10px;
  font-size: 12px;
  color: #909399;
  text-align: center;
  background: #fafbfc;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.recording-tip.error {
  color: #f56c6c;
  background: #fef0f0;
  border-color: #fbc4c4;
}

.recording-tip i {
  margin-right: 5px;
}

.clear-audio-btn {
  margin-left: 10px;
  color: #f56c6c;
}

.clear-audio-btn:hover {
  color: #f78989;
}

.tts-input-container {
  margin-bottom: 10px;
}

.tts-input-container .el-textarea {
  margin-bottom: 10px;
}
</style>
